"use client"

import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import {
	Form,
	FormControl,
	FormField,
	FormItem,
	FormLabel,
	FormMessage,
  } from "@/components/ui/form"
import { zodResolver } from "@hookform/resolvers/zod"
import { useForm } from "react-hook-form"
import { z } from "zod";
import { useTranslation } from '../../i18n/client'
import { login } from "@/lib/apiSet/login";
import { LoginRequest } from "@/lib/models/LoginRequest";
import { isLogged, saveAuthToken } from "@/lib/utils";
import { useRouter } from "next/navigation";
import { useEffect } from "react";

const formSchema = z.object({
	username: z.string().min(2).max(50),
	password: z.string().min(6).max(50),
  });

export default function LoginForm({ params: { lng } }: { params: { lng: string } }) {

	const router = useRouter();

	useEffect(() => {
	  // 假设你使用localStorage来存储登录状态
	  if (isLogged()) {
		// 如果用户已经登录，重定向到仪表盘页
		router.push('/dashboard');
	  }
	}, [router]);

	const { t } = useTranslation(lng);

	// 1. Define your form.
	const form = useForm<z.infer<typeof formSchema>>({
		resolver: zodResolver(formSchema),
		defaultValues: {
		  username: "",
		  password: "",
		},
	});

	// 2. Define a submit handler.
	function onSubmit(values: z.infer<typeof formSchema>) {
		// Do something with the form values.
		// ✅ This will be type-safe and validated.
		console.log(values);
		const request=new LoginRequest(values.username, values.password);
		login(request).then((res) => {
			console.log(res);
			// save token to local storage
			saveAuthToken(res.getToken());
		}).catch((err) => {
			console.log(err);
		});
	};

	return (
		<main className="flex min-h-screen flex-col items-center justify-between p-24">
			<div className="flex min-h-full flex-col justify-center px-6 py-12 lg:px-8">
			<div className="sm:mx-auto sm:w-full sm:max-w-sm">
				<h2 className="mt-10 text-center text-2xl font-bold leading-9 tracking-tight text-gray-900">{t('title')}</h2>
			</div>

			<div className="mt-10 sm:mx-auto sm:w-full sm:max-w-sm">
				<Form {...form}>
				<form onSubmit={form.handleSubmit(onSubmit)} className="space-y-8">
				<FormField
					control={form.control}
					name="username"
					render={({ field }) => (
						<FormItem>
						<FormLabel>Username</FormLabel>
						<FormControl>
							<Input {...field} />
						</FormControl>
						<FormMessage />
						</FormItem>
					)}
					/>

				<FormField
					control={form.control}
					name="password"
					render={({ field }) => (
						<FormItem>
						<FormLabel>Password</FormLabel>
						<FormControl>
							<Input type="password" {...field} />
						</FormControl>
						<FormMessage />
						</FormItem>
					)}
					/>

				<div>
					<Button type="submit">Sign in</Button>
				</div>
				</form>
				</Form>

			</div>
			</div>
		</main>
	);
}
